package com.umeox.moto.common.utils;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Pair;

import com.umeox.moto.common.BuildConfig;
import com.umeox.moto.common.log.LogUtils;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * Created by Shaozy on 2018/3/1.
 */

public class AndroidUtils {
    private static final String TAG = AndroidUtils.class.getSimpleName();
    //Ethernet Mac Address
    private static final String ETH0_MAC_ADDRESS = "/sys/class/net/eth0/address";
    public static final String VOLTE_NODE = "/data/volte_info";

    /**
     * 获取 Wifi MAC 地址
     * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     */
    @Deprecated
    public static String getMacAddress() {
        return getWifiMacAddress();
    }

    /**
     * 获取 Wifi MAC 地址
     * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     */
    public static String getWifiMacAddress() {
        //wifi mac地址
        WifiManager wifi = (WifiManager) AppUtils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String mac = info.getMacAddress();
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "WIFI MAC：" + mac);
        }
        return mac;
    }

    public static String getMacAddress1() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "02:00:00:00:00:00";
    }


    /**
     * 获取 以太网 MAC 地址
     */
    public static String getEthernetMacAddress() {
        try {
            String mac = FileUtils.readFile(ETH0_MAC_ADDRESS);
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "Ethernet MAC：" + mac);
            }
            return mac;
        } catch (Exception e) {
            Log.e(TAG, "IO Exception when getting eth0 mac address", e);
            e.printStackTrace();
            return "unknown";
        }
    }

    /**
     * 获取voLTE状态
     *
     * @return true 开
     */
    public static boolean isVoLTEEnable() {
        int count = 0;
        FileInputStream in = null;
        BufferedReader bReader = null;
        try {
            File fp = new File(VOLTE_NODE);
            in = new FileInputStream(fp);
            bReader = new BufferedReader(new InputStreamReader(in));
            String str = bReader.readLine();
            count = Integer.valueOf(str);
        } catch (Exception e) {
            Log.v("voLTE", "getStepCounts: ", e);
        } finally {
            close(in);
            close(bReader);
        }
        return count == 1;
    }

    public static boolean isVoLTEEnabled(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            try {
                Method method = TelephonyManager.class.getDeclaredMethod("isVolteAvailable");
                return (boolean) method.invoke(telephonyManager);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 关流
     *
     * @param in
     */
    private static void close(Closeable in) {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取 ANDROID_ID
     */
    public static String getAndroidId() {
        String androidId = Settings.Secure.getString(AppUtils.getApp().getContentResolver(), Settings.Secure.ANDROID_ID);
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "ANDROID_ID ：" + androidId);
        }
        return androidId;
    }

    /**
     * 获取 Device_ID
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getDeviceId() {
        TelephonyManager telephonyManager = (TelephonyManager) AppUtils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            deviceId = getIMEI(0);
        } else {
            deviceId = telephonyManager.getDeviceId();
        }
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "Device_ID ：" + deviceId);
        }
        return deviceId;

//        return "868792030116167";
    }


    /**
     * @param slotId slotId为卡槽Id，它的值为 0、1；
     * @return
     */
    public static String getIMEI(int slotId) {
        try {
            TelephonyManager manager = (TelephonyManager) AppUtils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
            Method method = manager.getClass().getMethod("getImei", int.class);
            String imei = (String) method.invoke(manager, slotId);
            return imei;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 根据设备WIFI MAC地址和IMEI的hashCode，生成UUID
     */
    public static String getDeviceUuid() {
        //Wifi Mac + IMEI
        String mac = getWifiMacAddress();
        LogUtils.d("Wifi Mac->" + mac);
        String imei = getDeviceId();
        LogUtils.d("Device IMEI->" + imei);

        UUID deviceUuid = UUID.nameUUIDFromBytes((imei + mac).getBytes());
        String uniqueId = deviceUuid.toString();
        LogUtils.d("UUID->" + uniqueId);
        return uniqueId;
    }

    /**
     * 获取系统属性
     */
    public static String getProperty(String key, String defaultValue) {
        String value = defaultValue;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, key, "unknown"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取系统版本号（非Android版本）
     */
    public static String getSystemVersion() {
        return getProperty("ro.build.display.id", "");
    }

    /**
     * 获取 开机时间
     */
    public static String getBootTimeString() {
        long ut = SystemClock.elapsedRealtime() / 1000;
        int h = (int) ((ut / 3600));
        int m = (int) ((ut / 60) % 60);
        if (BuildConfig.DEBUG) {
            Log.i(TAG, h + ":" + m);
        }
        return h + ":" + m;
    }

    /**
     * 获取基站信息
     */
    @SuppressLint("MissingPermission")
    public static Pair<Integer, Integer> getCellInfo() {
        /** 调用API获取基站信息 */
        TelephonyManager tel = (TelephonyManager) AppUtils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
        //IMSI：国际移动用户识别码（唯一标识）
        // IMSI = MCC + MNC + MSIN
        // MCC是指移动台国家代码（3 位，中国460）
        // MNC是指移动网代码（2 位中国00）
        // MSIN是指移动用户识别号码 (10 位 )
        String mm;
        if (tel.getSimState() == TelephonyManager.SIM_STATE_READY) {
            mm = tel.getSimOperator();
        } else {
            mm = tel.getSubscriberId();
        }
        LogUtils.i("mcc+mnc：" + mm);
        if (!StringUtils.isEmpty(mm) && mm.length() >= 5) {
            if (mm.startsWith("46000")
                    || mm.startsWith("46002")) {
                //因为移动网络编号46000下的IMSI已经用完，所以虚拟了一个46002编号，134/159号段使用了此编号
                //中国移动
                LogUtils.i("中国移动");
            } else if (mm.startsWith("46001")
                    || mm.startsWith("46006") || mm.startsWith("46009")) {
                //中国联通
                LogUtils.i("中国联通");
            } else if (mm.startsWith("46003")) {
                //中国电信
                LogUtils.i("中国电信");
            } else {
                LogUtils.i("未知运营商");
            }
            int mcc = Integer.parseInt(mm.substring(0, 3));
            int mnc = Integer.parseInt(mm.substring(3, 5));
            return new Pair<>(mcc, mnc);
        } else {
            return new Pair<>(-1, -1);
        }
    }

    public static int getMCC() {
        try {
            Pair<Integer, Integer> cellInfo = getCellInfo();
            return cellInfo.first;
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("Get MCC failed :" + e.getMessage());
            }
        }
        return -1;
    }

    public static String getHexMcc() {
        return Integer.toHexString(getMCC());
    }

    public static int getMNC() {
        try {
            Pair<Integer, Integer> cellInfo = getCellInfo();
            return cellInfo.second;
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("Get MNC failed :" + e.getMessage());
            }
        }
        return -1;
    }

    public static String getHexMnc() {
        return Integer.toHexString(getMNC());
    }

    /**
     * 获取系统默认闹钟铃声
     */
    public static int getAlarmRingtonePosition() {
        RingtoneManager rm = new RingtoneManager(AppUtils.getApp());
        rm.setType(RingtoneManager.TYPE_ALARM);
        Uri uri = RingtoneManager.getActualDefaultRingtoneUri(AppUtils.getApp(), RingtoneManager.TYPE_ALARM);
        return rm.getRingtonePosition(uri);
    }

    /**
     * 设置系统默认闹钟铃声
     */
    public static Ringtone getAlarmRingtone(int position) {
        RingtoneManager rm = new RingtoneManager(AppUtils.getApp());
        rm.setType(RingtoneManager.TYPE_ALARM);
        Cursor mCurson = rm.getCursor();
        Uri notification = null;
        if (mCurson != null && position > 0 && position < mCurson.getCount() - 1) {
            notification = rm.getRingtoneUri(position);
        }
        if (notification == null) {
            notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        }
        if (notification != null) {
            return rm.getRingtone(position);
        }
        return null;
    }

    /**
     * 在min和max之间取一个随机数
     */
    public static int getRandom(int min, int max) {
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }

    public static long getAvailableInternalMemory() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        return availableBlocks * blockSize;
    }


    public static String getCurrentApnName(Context context) {
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        //获取网络接入点，中国移动:cmwap和cmnet; 中国电信ctwap，ctnet
        if (ni != null) {
            LogUtils.i("info:" + ni.toString());
            return ni.getExtraInfo();
        }
        return "unknow";
    }

    public static boolean isBluetoothEnable() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter.isEnabled();
    }
}
